﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.Runtime;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

namespace K9Nano.EFCore
{
    public class K9DbContext : DbContext, IK9DbContext
    {
        protected IDbContextHelper Helper { get; }

        public K9DbContext(DbContextOptions options, IDbContextHelper helper)
            : base(options)
        {
            Helper = helper;
            Helper.DbContext = this;
        }

        public ISessionContext SessionContext => Helper.SessionContext;

        public virtual bool FiltersDisabled
        {
            get => Helper.FiltersDisabled;
            set => Helper.FiltersDisabled = value;
        }

        public virtual bool SuppressAutoSetTenantId
        {
            get => Helper.SuppressAutoSetTenantId;
            set => Helper.SuppressAutoSetTenantId = value;
        }

        public virtual bool EventsDisabled
        {
            get => Helper.EventsDisabled;
            set => Helper.EventsDisabled = value;
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            Helper.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            return Helper.SaveChanges(acceptAllChangesOnSuccess, base.SaveChanges);
        }

        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellation = default)
        {
            return Helper.SaveChangesAsync(acceptAllChangesOnSuccess, cancellation, base.SaveChangesAsync);
        }

        public virtual IQueryable<TEntity> Queryable<TEntity>() where TEntity : class
        {
            return Helper.Queryable<TEntity>();
        }

        public virtual IDbContextTransaction BeginTransaction()
        {
            return base.Database.BeginTransaction();
        }
    }
}
